package client

import (
	"OJCenter/global"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

type Client struct {
	Cli *http.Client
	c   chan os.Signal
}

func NewClient() (*Client, error) {
	ch := make(chan os.Signal, 1)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
	return &Client{
		Cli: nil,
		c:   ch,
	}, nil

}

// Ping 心跳检测
func (c *Client) Ping() {
	var err error
	timeStamp, err := time.ParseDuration(global.Conf.HttpConf.ClientConf.PingDuration)
	if err != nil {
		global.Logger.Errorf("heartbeat timeStamp err")
		return
	}
	select {
	case <-c.c:
		global.Logger.Infof("heart beat close by signal")
		return
	default:
	}
	if timeStamp < 0 {
		timeStamp, _ = time.ParseDuration("5s")
	}
	ticker := time.NewTicker(timeStamp)
	defer func() {
		ticker.Stop()
		global.Logger.Infof("heart beat close")
	}()
	for {
		select {
		case <-c.c:
			global.Logger.Infof("heart beat close by signal")
			return
		//case newInterval := <-reset:
		//	if !timer.Stop() {
		//		<-timer.C
		//	}
		//	if newInterval > 0 {
		//		interval = newInterval
		//	}
		case <-ticker.C:
			res, err := http.Get(global.Conf.HttpConf.ClientConf.PingUrl)
			if err != nil {
				global.Logger.Errorf("heatbeat failed,err:%v", err)
				continue
			}
			global.Logger.Infof("heatbeat:%v", res)
			//在此跟踪并执行连续超时
		}
	}
}
